package com.wl.shixun4.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wl.shixun4.dao.ProductDAO;
import com.wl.shixun4.entity.Product;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

/**
 * 产品API Servlet - 实训任务四
 * 处理添加、编辑、删除、查询单个记录的API请求
 */
@WebServlet("/shixun4/api/*")
public class ProductAPIServlet extends HttpServlet {
    
    private ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        response.setContentType("application/json; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        
        String pathInfo = request.getPathInfo();
        Map<String, Object> responseData = new HashMap<>();
        
        try {
            if (pathInfo.endsWith("/add")) {
                handleAdd(request, response, responseData);
            } else if (pathInfo.endsWith("/update")) {
                handleUpdate(request, response, responseData);
            } else if (pathInfo.endsWith("/delete")) {
                handleDelete(request, response, responseData);
            } else {
                responseData.put("success", false);
                responseData.put("message", "未知操作");
                sendResponse(response, responseData);
            }
        } catch (Exception e) {
            responseData.put("success", false);
            responseData.put("message", "操作失败: " + e.getMessage());
            sendResponse(response, responseData);
        }
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        response.setContentType("application/json; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        
        String pathInfo = request.getPathInfo();
        Map<String, Object> responseData = new HashMap<>();
        
        try {
            if (pathInfo.endsWith("/get")) {
                handleGet(request, response, responseData);
            } else {
                responseData.put("success", false);
                responseData.put("message", "未知操作");
                sendResponse(response, responseData);
            }
        } catch (Exception e) {
            responseData.put("success", false);
            responseData.put("message", "操作失败: " + e.getMessage());
            sendResponse(response, responseData);
        }
    }
    
    /**
     * 处理添加操作
     */
    private void handleAdd(HttpServletRequest request, HttpServletResponse response, 
                          Map<String, Object> responseData) throws IOException {
        try {
            // 读取JSON请求体
            String jsonBody = readRequestBody(request);
            Map<String, Object> data = objectMapper.readValue(jsonBody, Map.class);
            
            String name = (String) data.get("name");
            String number = (String) data.get("number");
            String price = (String) data.get("price");
            String madetime = (String) data.get("madetime");
            
            // 验证必填字段
            if (name == null || name.trim().isEmpty() ||
                number == null || number.trim().isEmpty() ||
                price == null || price.trim().isEmpty() ||
                madetime == null || madetime.trim().isEmpty()) {
                responseData.put("success", false);
                responseData.put("message", "所有字段都是必填的");
                sendResponse(response, responseData);
                return;
            }
            
            // 使用 ProductDAO 的方法添加
            boolean success = ProductDAO.insertFromParams(number, name, price, madetime);
            responseData.put("success", success);
            responseData.put("message", success ? "记录添加成功" : "记录添加失败");
            
        } catch (Exception e) {
            responseData.put("success", false);
            responseData.put("message", "添加失败: " + e.getMessage());
        }
        
        sendResponse(response, responseData);
    }
    
    /**
     * 处理编辑操作
     */
    private void handleUpdate(HttpServletRequest request, HttpServletResponse response,
                             Map<String, Object> responseData) throws IOException {
        try {
            // 读取JSON请求体
            String jsonBody = readRequestBody(request);
            Map<String, Object> data = objectMapper.readValue(jsonBody, Map.class);
            
            long id = Long.parseLong(data.get("id").toString());
            String name = (String) data.get("name");
            String number = (String) data.get("number");
            String price = (String) data.get("price");
            String madetime = (String) data.get("madetime");
            
            // 验证必填字段
            if (name == null || name.trim().isEmpty() ||
                number == null || number.trim().isEmpty() ||
                price == null || price.trim().isEmpty() ||
                madetime == null || madetime.trim().isEmpty()) {
                responseData.put("success", false);
                responseData.put("message", "所有字段都是必填的");
                sendResponse(response, responseData);
                return;
            }
            
            // 构建 Product 对象
            Product product = new Product();
            product.setId(id);
            product.setName(name);
            product.setNumber(number);
            product.setPrice(price);
            
            // 处理 datetime-local 格式的日期时间字符串 (格式: yyyy-MM-ddTHH:mm)
            String datetimeStr = madetime.replace("T", " ") + ":00";
            product.setMadetime(Timestamp.valueOf(datetimeStr));
            
            boolean success = ProductDAO.update(product);
            responseData.put("success", success);
            responseData.put("message", success ? "记录更新成功" : "记录更新失败");
            
        } catch (Exception e) {
            responseData.put("success", false);
            responseData.put("message", "更新失败: " + e.getMessage());
        }
        
        sendResponse(response, responseData);
    }
    
    /**
     * 处理删除操作
     */
    private void handleDelete(HttpServletRequest request, HttpServletResponse response,
                             Map<String, Object> responseData) throws IOException {
        try {
            long id = Long.parseLong(request.getParameter("id"));
            
            boolean success = ProductDAO.delete(id);
            responseData.put("success", success);
            responseData.put("message", success ? "记录删除成功" : "记录删除失败");
            
        } catch (Exception e) {
            responseData.put("success", false);
            responseData.put("message", "删除失败: " + e.getMessage());
        }
        
        sendResponse(response, responseData);
    }
    
    /**
     * 处理获取单个记录
     */
    private void handleGet(HttpServletRequest request, HttpServletResponse response,
                          Map<String, Object> responseData) throws IOException {
        try {
            long id = Long.parseLong(request.getParameter("id"));
            
            Product product = ProductDAO.getById(id);
            if (product != null) {
                Map<String, Object> productMap = new HashMap<>();
                productMap.put("id", product.getId());
                productMap.put("name", product.getName());
                productMap.put("number", product.getNumber());
                productMap.put("price", product.getPrice());
                productMap.put("madetime", product.getMadetime() != null ? 
                              product.getMadetime().toString() : null);
                
                responseData.put("success", true);
                responseData.put("data", productMap);
            } else {
                responseData.put("success", false);
                responseData.put("message", "记录不存在");
            }
            
        } catch (Exception e) {
            responseData.put("success", false);
            responseData.put("message", "查询失败: " + e.getMessage());
        }
        
        sendResponse(response, responseData);
    }
    
    /**
     * 读取请求体
     */
    private String readRequestBody(HttpServletRequest request) throws IOException {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }
        return sb.toString();
    }
    
    /**
     * 发送JSON响应
     */
    private void sendResponse(HttpServletResponse response, Map<String, Object> data) throws IOException {
        PrintWriter out = response.getWriter();
        out.print(objectMapper.writeValueAsString(data));
        out.flush();
    }
}

